<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['app_dir'] . "/includes/db.class.php");
    require_once($config['app_dir'] . "/includes/date.class.php");
    require_once($config['app_dir'] . '/includes/template.class.php');
    require_once($config['app_dir'] . '/includes/session.class.php');
    require_once($config['app_dir'] . '/includes/date.class.php');
    require_once($config['app_dir'] . '/includes/number.class.php');
    require_once($config['app_dir'] . '/classes/class.calc2.php');
    require_once($config['app_dir'] . '/classes/DataLists.class.php');
    require_once($config['app_dir'] . '/classes/forecasts.deamon.php');
    require_once($config['app_dir'] . '/classes/archive.class.php');
    require_once($config['app_dir'] . '/classes/user.data.php');
    //----------------------------------------------------------------------------------------------------
    class objTrackCalculator {
            public $mode = 'pair'; //pair or system
            public $short = true;
            public $enable_active = false;
            public $active_period = false;
            public $dateStart = false;
            public $dateFinish = false;
            public $pairs = false;
            public $systems = false;
            public $start_year = '2006';
            public $start_month = '01';
            //public $selPair = 1;//2400203; //1 means all

            public $flag_show_column_all = false;

            public $selDataKey = 0;// //0 means all

            public $disabled_periods = array();
            public $template_filename = '_TracksPeriod.tpl';

            public $system = 0;

            public $TranslationMessage = false;

            protected $Calculator = false;
            protected $Template = false;
            protected $data = array();
            protected $id = false;
            protected $performed = false;

            protected $datesArr = array();
            protected $itemsArr = array();
            protected $pairsArr = array();
            protected $systemsArr = array();
            protected $itemsAllArr = array();//XXX ????
            protected $totalsArr = array();

        public function __construct($aActivePeriod=false) {
            $this->active_period = $aActivePeriod;

            $this->Calculator = new objCalculator();
            //----------------------------------------------------------------------
            $this->Calculator->slippage = 0;
            $this->Calculator->contract = 100000;
            $this->Calculator->balance = 100000;
            $this->Calculator->deposit = 10000;
            //----------------------------------------------------------------------
            $this->Template = new objTemplate();
        } //constructor

        protected function GenID($cntForecast) {
            $this->id = 'tracks_' . md5($this->mode . implode(',', $this->pairs).'_'.$this->dateStart.'_'.$this->dateFinish.'_'.$cntForecast.'_'.$this->short.'_'.$this->system);
            return $this->id;
        } //GenId

        protected function isCached() {
            return $this->id && $this->Template->is_cached($this->template_filename, $this->id);
        } //isCached

        public function clearDisabledPeriods() {
            $this->disabled_periods = array();
        } //setDisabledPeriods

        public function setDisabledPeriods($aPeriods) {
            $this->disabled_periods = $aPeriods;
        } //setDisabledPeriods

        public function addDisabledPeriods($aPeriods) {
            if( is_array($aPeriods) ) $this->disabled_periods = array_merge($this->disabled_periods, $aPeriods);
                else $this->disabled_periods[] = $aPeriods;
        } //addDisabledPeriods

        protected function GetPairs() {
            $Pairs = new objPairsSystems();
            if( 'system'!=$this->mode ) $Pairs->system = $this->system;

            $PairsSystems->order_by_rate = false;
            $PairsSystems->order_by_sysname = true;

            $this->pairs = array();
            $this->pairsArr = $Pairs->GetAssocArr();
            foreach( $this->pairsArr as $pairItem) {
                $this->pairs[] = $pairItem['TradeID'];
            } //foreach

            $this->Calculator->getPairs();

            return $this->pairs;
        }//getPairs

        protected function GetSystems() {
            $PairsSystems = new objPairsSystems();
            $PairsSystems->order_by_rate = false;
            $PairsSystems->order_by_sysname = true;

            $this->systems = array();
            $this->systemsArr = $PairsSystems->GetAssocArr();
            $no = 0;
            foreach( $this->systemsArr as $pairItem) {
                $this->systems[$pairItem['SystemID']][] = $pairItem['TradeID'];
                $this->index_system_by_no[$pairItem['SystemID']] = $no++;
            } //foreach

            return $this->systems;
        } //getSystems

        protected function Period() {
            $finish_year = intval(DateConvert::Date('Y'));
            $finish_month = intval(DateConvert::Date('m'));

            if( $this->active_period ) {
                $start_year = $finish_year;
                $start_month = $finish_month;
            } else {
                $start_year = $this->start_year;
                $start_month = $this->start_month;
            }

            $this->Calculator->formDate($start_year, $start_month, $finish_year, $finish_month);

            $this->dateStart = DateConvert::Date('Y-m-d', $this->Calculator->timeRange[0]);
            $this->dateFinish = DateConvert::Date('Y-m-d', $this->Calculator->timeRange[1]);
        } //Period


        protected function CalculateBySystem($force=false) {
            if( !$force && $this->performed ) return true;

            $this->flag_show_column_all = false;

            $this->GetPairs();
            $this->GetSystems();

            $this->Calculator->enable_active = $this->enable_active;
            $this->Calculator->setDisabledPeriods($this->disabled_periods);

            $index = 0;
            $this->data = array();
            if( !$this->short  || 0 != $this->selDataKey ) {

                foreach($this->systemsArr as $systemItem)
                    if( !$this->short || $systemItem['SystemID'] == $this->selDataKey ) {
                        $this->Calculator->Clear();
                        $this->Calculator->system = $systemItem['SystemID'];
                        $this->Calculator->trades = $this->systems[$systemItem['SystemID']];

                        $this->Calculator->getForecastData($this->Calculator->timeRange[0],$this->Calculator->timeRange[1],
                                                               $pairItem['TradeID'], $this->Calculator->trades);

                        $this->data[$index]['DataItem'] = $systemItem;
                        $this->data[$index]['DataItem']['DataID'] = $systemItem['SystemID'];
                        if( 0===strpos($systemItem['SysName'], 'IntelliForex') ) {
                            $systemItem['SysName'] = substr($systemItem['SysName'], 13);
                        }
                        $this->data[$index]['DataItem']['DataName'] = $systemItem['SysName'];
                        $this->data[$index]['statsArr'] = $this->Calculator->statsArr;
                        $this->data[$index]['totalsArr'] = $this->Calculator->calculateTotals();

                        $index++;
                    } //foreach system

            } //if building detailed table

            if( !$this->short || 0==$this->selDataKey ) {
                $this->Calculator->Clear();

                $this->Calculator->getForecastData($this->Calculator->timeRange[0], $this->Calculator->timeRange[1], false, $this->pairs);

                $this->data[$index]['DataItem']['DataName'] = $this->TranslationMessage->GetMessage('_tracks__labelAll');
                $this->data[$index]['DataItem']['DataID'] = '0';

                $this->data[$index]['statsArr'] = $this->Calculator->statsArr;
                $this->data[$index]['totalsArr'] = $this->Calculator->calculateTotals();
                $index++;
            }//if

            return $index;
        } //CaluclateBySystem

        protected function CalculateByPair($force=false){
            if( !$force && $this->performed ) return true;

            $this->flag_show_column_all = true;

            $this->GetPairs();
            $this->GetSystems();

            $this->Calculator->system = $this->system;
            $this->Calculator->enable_active = $this->enable_active;
            $this->Calculator->setDisabledPeriods($this->disabled_periods);

            //------------------------------------------------------------
            $this->data = array();
            $index = 0;
            if( !$this->short || 0!=$this->selDataKey ) {
                foreach($this->Calculator->pairsArr as $pairItem)
                    if( !$this->short || $pairItem['TradeID'] == $this->selDataKey ) {

                        $this->Calculator->Clear();
                        $this->Calculator->trades = array($pairItem['TradeID']);

                        $this->Calculator->getForecastData($this->Calculator->timeRange[0], $this->Calculator->timeRange[1],
                                                           $pairItem['TradeID'], $this->Calculator->trades);

                        $this->data[$index]['DataItem'] = $pairItem;
                        $this->data[$index]['DataItem']['DataID'] = $pairItem['TradeID'];
                        $this->data[$index]['DataItem']['DataName'] = $pairItem['Pair'];
                        $this->data[$index]['statsArr'] = $this->Calculator->statsArr;
                        $this->data[$index]['totalsArr'] = $this->Calculator->calculateTotals();

                        $index++;
                    } //if+foreach
            }//show if mode is not short
            //----------------------------------------------------------------------
            // total pairs
            //----------------------------------------------------------------------
            if( !$this->short || 0==$this->selDataKey ) {
                $this->Calculator->Clear();

                $this->Calculator->getForecastData($this->Calculator->timeRange[0], $this->Calculator->timeRange[1], false, $this->pairs);

                $this->data[$index]['DataItem']['DataName'] = $this->TranslationMessage->GetMessage('_tracks__labelAll');
                $this->data[$index]['DataItem']['DataID'] = '0';

                $this->data[$index]['statsArr'] = $this->Calculator->statsArr;
                $this->data[$index]['totalsArr'] = $this->Calculator->calculateTotals();
                $index++;
            }//if
            return $index;
        } //CalculateByPair

        public function Calculate($force=false) {
            $result = false;
            switch( strtolower($this->mode) ) {
                case 'system':
                    $result = $this->CalculateBySystem($force);
                break;

                case 'pair':
                default:
                    $result = $this->CalculateByPair($force);
            } //switch
            return $result;
        } //Calculate

        protected function ConvertData(){
            if( !$force && $this->performed ) return true;

            $data = array();
            $datesArr = array();
            $dataArr = array();
            $totalsArr = array();

            foreach($this->data as $itemData) {

                $item = $itemData['DataItem'];

                if( !array_key_exists($item['DataKey'], $dataArr) ) {
                    $dataArr[ $item['DataID'] ]['ID'] = $item['DataID'];
                    $dataArr[ $item['DataID'] ]['Name'] = $item['DataName'];
                }

                foreach( $itemData['statsArr'] as $itemStat ) {
                    if( !array_key_exists($itemStat['dateKey'], $datesArr) ) {
                        $datesArr[ $itemStat['dateKey'] ]['DateKey'] = $itemStat['dateKey'];
                        $datesArr[ $itemStat['dateKey'] ]['Year'] = $itemStat['year'];
                        $datesArr[ $itemStat['dateKey'] ]['Date'] = $itemStat['date'];
                        $datesArr[ $itemStat['dateKey'] ]['Start'] = $itemStat['start'];
                        $datesArr[ $itemStat['dateKey'] ]['Finish'] = $itemStat['finish'];
                        $datesArr[ $itemStat['dateKey'] ]['Active'] = $this->enable_active;
                    }//if not exists key

                    $data[ $itemStat['dateKey'] ][ $item['DataID'] ] = $itemStat['pips'];
                } //foreach Stats

                $totalsArr[ $item['DataID'] ]['pips'] = $itemData['totalsArr']['pips'];
                $totalsArr[ $item['DataID'] ]['months'] = $itemData['totalsArr']['months'];
            }//foreach
            unset($this->data);

            uksort($datesArr, array($this,'compareDateItems'));
            uksort($data, array($this,'compareDateItems'));

            $this->data = $data;
            $this->datesArr = $datesArr;
            $this->itemsArr = $dataArr;
            $this->totalsArr = $totalsArr;
            $this->performed = true;

            return true;
        } //convertData

        protected function compareDateItems($key1, $key2) {
            $k1 = intval($key1);
            $k2 = intval($key2);

            if( $k1 == $k2 ) {
                return 0;
            }
            return ($k1 > $k2) ? -1 : 1;
        }//compareDateItems

        protected function Perform() {
            $this->Period();
            if( !$this->Calculate() ) return false;
            $this->ConvertData();
            return false;
        } //Perform

        public function GetData() {
            $this->Period();
            if( !$this->Calculate() ) return false;
            $this->ConvertData();
            return array('data'=>$this->data, 'dates' => $this->datesArr,
                         'items' => $this->itemsArr, 'systems' => $this->systemsArr,
                         'totals' => $this->totalsArr);
        } //GetData

        public function GetLast() { //XXX
            $this->Perform();

            reset($this->itemsArr);
            $dataItem = current($this->itemsArr);
            reset($this->datesArr);
            $datesItem = current($this->datesArr);

            return array(
                            'TradeID' => $dataItem['DataID'], //XXX
                            'value' => $this->data[ $datesItem['DateKey'] ][ $dataItem['DataID'] ],
                            'DateStart' => $datesItem['Start'],
                            'DateFinish' => $datesItem['Finish'],
                            'Active' => $datesItem['Active'],
                            'System' => $this->system
                            );
        }//getLast

        public function Render() {
            if( $this->Perform() ) return false;
            //----------------------------------------------------------------------
            $this->Template->Assign('mode', $this->mode);
            $this->Template->Assign('short', $this->short);
            $this->Template->Assign('SystemID', $this->system);
            $this->Template->Assign('data', $this->data);
            $this->Template->Assign('datesArr', $this->datesArr);
            $this->Template->Assign('itemsArr', $this->itemsArr);
            $this->Template->Assign('systemsArr', $this->systemsArr);
            $this->Template->Assign('systemByNoInd', $this->index_system_by_no);
            $this->Template->Assign('totalsArr', $this->totalsArr);
            $this->Template->Assign('flagShowColumnAll', $this->flag_show_column_all);
            //----------------------------------------------------------------------
            return $this->Template->Fetch($this->template_filename);
        } //Render

        public function RenderPerfTable($perfTableDateKey) {
            if( $this->Perform() ) return false;
            //----------------------------------------------------------------------
            $this->Template->Assign('signalsPerf', true);
            $this->Template->Assign('data', $this->data);
            $this->Template->Assign('datesArr', $this->datesArr);
            $this->Template->Assign('itemsArr', $this->itemsArr);
            $this->Template->Assign('selectedDateKey',$perfTableDateKey);
            //----------------------------------------------------------------------
            return $this->Template->Fetch('_PerformanceBlockItem.tpl');
        } //Render

        public function Dump($flag_echo = true) {
            if( $flag_echo ) var_dump($this->data);
            else return var_export($this->data, true);
        } //Dump

    }//TrackCalculator

    //----------------------------------------------------------------------------------------------------

    class objTracks {

            public $template_filename = '_Tracks.tpl';
            public $TranslationMessage = false;
            public $enable_active = false;
            public $system = 0;

        public function Render() {
          global $config;

            $SystemSelector = new objSystemSelector($config['system']['default'], true);
            $SystemSelector->action_script = "xajax_showTrackRecord(0, document.getElementById('id_selectsystem_system').value);";

            $Template = new objTemplate();
            $Template->Assign('formSystemSelector', $SystemSelector->Render());

            return $Template->Fetch($this->template_filename);
        }//Render

    }//class objTracks
    //----------------------------------------------------------------------------------------------------

    class objTrackRecordCollector {
            private static $instance;
            private $prefix = 'SelectedTracks_';
            protected $Session = false;

        protected function __construct() {
          global $config;
            $this->Session = new objSession($config['app_id']);
        } //constructor

        public static function GetInstance() {
            if (!isset(self::$instance)) {
                $c = __CLASS__;
                self::$instance = new $c;
            }
            return self::$instance;
        } //GetInstance

        public function __clone() {
            throw new Exception('Cant clone singleton');
        } //clone
        //---------------------------------------------------------------------
        public function isEmpty() {
            return !$this->Session->isExists($this->prefix . 'start') || !$this->Session->Get($this->prefix . 'start') ||
                   !$this->Session->isExists($this->prefix . 'finish') || !$this->Session->Get($this->prefix . 'finish');
        } //isEmpty

        public  function Lock() {
            $this->Session->Put($this->prefix . 'lock', "1");
        } //Lock

        public function Unlock() {
            $this->Session->Put($this->prefix . 'lock', "0");
        } //Unlock

        public function isLocked() {
            return $this->Session->Get($this->prefix . 'lock');
        } //Unlock

        public function IncCounter() {
            $this->Session->Put($this->prefix . 'count', 1 + $this->getCounter());
        } //IncCounter

        public function getCounter() {
            return intval($this->Session->Get($this->prefix . 'count'));
        } //getCounter

        public function setTrackItem($aValue) {
            $this->Session->Put($this->prefix . 'trade', $aValue['trade']);
            $this->Session->Put($this->prefix . 'active', $aValue['show_active']);
            $this->Session->Put($this->prefix . 'system', $aValue['system']);
            $this->Session->Put($this->prefix . 'mode', $aValue['mode']);
        } //setTrackItem

        public function getTrackItem() {
            $result = array();

            $result['trade'] = $this->Session->Get($this->prefix . 'trade');
            $result['show_active'] = $this->Session->Get($this->prefix . 'active');
            $result['system'] = $this->Session->Get($this->prefix . 'system');
            $result['mode'] = $this->Session->Get($this->prefix . 'mode');

            return $result;
        } //getTrackItem

        public function getForecastItem() {
            $result = array();

            $result['start'] = $this->Session->Get($this->prefix . 'start');
            $result['finish'] = $this->Session->Get($this->prefix . 'finish');

            return $result;
        } //getForecastItem

        public function setForecastItem($aValue) {
            $this->Session->Put($this->prefix . 'start', $aValue['start']);
            $this->Session->Put($this->prefix . 'finish', $aValue['finish']);
        } //setForecastItem

        public function Clear($name=false) {
            if( !$name ) {
                $this->Session->Put($this->prefix . 'start', false);
                $this->Session->Put($this->prefix . 'finish', false);
                $this->Session->Put($this->prefix . 'trade', false);
                $this->Session->Put($this->prefix . 'mode', false);
                $this->Session->Put($this->prefix . 'active', 0);
                $this->Session->Put($this->prefix . 'system', false);
            } else {
                $this->Session->Put($this->prefix . $name, false);
            }

        } //Clear

    } //class TrackRecordCollector

    //----------------------------------------------------------------------------------------------------

    class objTrackForecastsShow extends objObject implements iErrorHandler{
            public $data = false;

            protected $enable_active = false;
            protected $_db = false;
            protected $_sql_querys = false;
            protected $select_limit = 0;
            protected $_trade = false;
            protected $_start = false;
            protected $_finish = false;
            protected $_system = false;
            protected $_db_param_date = '%Y-%m-%d';
            protected $_db_show_date = '%b %e';//'%m-%d-%Y';
            protected $_error_str = array('no error',//0
                                          'Input parameters are empty'//1
                                         );

        public function __construct($trade=false, $start, $finish, $system=false) {
            $this->_trade = $trade;
            $this->_start = $start;
            $this->_finish = $finish;
            $this->_system = $system;

            //if( !$this->_start && !$this->_finish) throw new Exception($this->Error(1));

            $this->_db = objDataBase::GetInstance();
            //$this->_sqls();
        } //constructor

        public function __set($name, $value) {

            switch( strtolower($name) ) {
                case 'enable_active' :
                    $this->enable_active = $value;
                    $this->_sqls();
                break;
            }//switch

        }//setter

        public function __get($name) {

            switch( strtolower($name) ) {
                case 'enable_active' :
                    return $this->enable_active;
                break;
            }//switch

        }//getter

        //-------------------------------------------------------------------------------------
        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function Dump() {
            echo "TradeID \n<br>";var_dump($this->_trade);
            echo "Start \n<br>";var_dump($this->_start);
            echo "Finish \n<br>";var_dump($this->_finish);
            echo "System \n<br>";var_dump($this->_system);
            echo "Data \n<br>";var_dump($this->data);
        } //dump

        //-------------------------------------------------------------------------------------

        protected function Prepare() {
            $this->_sqls();
            $this->data = $this->_db->handler->getAll($this->_sql_querys['forecast_list']);
            $this->PostPrepare();
            return $this->data;
        }//Prepare

        protected function PostPrepare() {
            for($i=0; $i<count($this->data); $i++) {
                $this->data[$i]['decimal'] = NumberConvert::decimal($this->data[$i]['PipSize']);;

                if( 0===strpos($this->data[$i]['SystemName'], 'IntelliForex') ) {
                    $this->data[$i]['SimpleSystemName'] = substr($this->data[$i]['SystemName'], 13);
                }
            } //for
        } //PostPrepare

        public function Render($templateFileName='_TrackForecasts.tpl') {
            if( !$this->Prepare() ) return false;

            $tList = new objTemplate();
            $tList->Assign('ForecastArr', $this->data);

            return $tList->Fetch($templateFileName);
        }//Render

        protected function buildWhere() {
            $whereArr = array();
            $whereArr[0] = array();
            if( $this->_trade )  $whereArr[0][] = "t.TradeId=$this->_trade";
            if( $this->_system )  $whereArr[0][] = "f.SystemID=$this->_system";
            //-----------------------------------------------------------------------------------
            $whereArr[1] = array();
            $whereArr[1][] = "f.CloseTime is not null";
            if( $this->_start )
                $whereArr[1][] = "FROM_UNIXTIME(f.CloseTime,'$this->_db_param_date') >= '$this->_start' ";
            if( $this->_finish )
                $whereArr[1][] = "FROM_UNIXTIME(f.CloseTime,'$this->_db_param_date') <= '$this->_finish' ";
            //-----------------------------------------------------------------------------------
            $whereArr[2] = array();
            if( $this->enable_active ) {
                $whereArr[2][] = "f.CloseTime is null";
                if( $this->_start )
                    $whereArr[2][] = "FROM_UNIXTIME(lq.LastCloseTime,'$this->_db_param_date') >= '$this->_start' ";
                if( $this->_finish )
                    $whereArr[2][] = "FROM_UNIXTIME(lq.LastCloseTime,'$this->_db_param_date') <= '$this->_finish' ";
            } //enable active
            //-----------------------------------------------------------------------------------
            for($i=0; $i<count($whereArr); $i++) {
                $whereArr[$i] = implode(' AND ', $whereArr[$i]);
                if( $whereArr[$i] ) $whereArr[$i] = '('. $whereArr[$i] .')';
            }//for

            $dates = $whereArr[1] . ($whereArr[1] && $whereArr[2] ? ' OR ' : '') . $whereArr[2];
            if( $dates ) $dates ="($dates)";
            return $whereArr[0] . ($whereArr[0] && $dates ? ' AND ' : '') . $dates;
        } //buildWhere

        protected function _sqls($aWhere=false) {
            $where = ($aWhere ? $aWhere : $this->buildWhere() );
            //------------------------------------------------------------------
            $this->_sql_querys['forecast_list'] =
            " SELECT f.ForecastID, (f.CloseTime is null) as FlagActive, f.BeginPrice, f.BeginTime,f.EndTime,f.EndPrice,t.PipSize, t.TradeID, t.Pair, f.Color, f.StopPrice, f.Side,f.SystemID, f.Size, ".

                    " round(f.Size * (1 - 2 * f.Side) * (COALESCE(f.ClosePrice, (1-f.Side)* r.Bid + f.Side*r.Ask, lq.LastClosePrice) - f.BeginPrice) / t.PipSize) as Profit, ".


                " f.BeginTime as BeginForecast, ".
                " COALESCE(f.EndTime, f.CloseTime, f.BeginTime+s.TimeFrame, lq.LastCloseTime) as EndForecast, ".


                " s.ShortName as SystemShortName, s.Name as SystemName, s.ChartPeriod, s.TimeFrame, s.ViewPeriod, ".
                $this->_db->handler->Concat('s.ShortName', 'f.ForecastID')." as SignalID, ".

                " FROM_UNIXTIME(f.BeginTime,'$this->_db_show_date') as OpenTimeF, " .
                " FROM_UNIXTIME(f.CloseTime,'$this->_db_show_date') as CloseTimeF, " .

                " COALESCE(f.CloseTime,lq.LastCloseTime) as CloseTime,   ".
                " COALESCE(f.ClosePrice,lq.LastClosePrice) as ClosePrice   ".

            " FROM vfa_forecast f ".
                   " LEFT OUTER JOIN fa_trades t ON (f.TradeID = t.TradeID) ".
                   " LEFT OUTER JOIN fa_systems s ON (f.SystemID = s.SystemID)  ".
                   " LEFT OUTER JOIN fa_rates r  ON (f.TradeID=r.TradeID)  ".
                   " LEFT OUTER JOIN ".
                     "(  ".
                      " SELECT ".
                           " ttq.TradeID, ".
                           " ttq.C as LastClosePrice, ".
                           " ttq.TimeStart as LastCloseTime ".
                      " FROM fa_quotes ttq ".
                          " RIGHT OUTER JOIN ( ".
                                " SELECT tq.TradeID, max(tq.TimeStart) as max_quote_time ".
                                " FROM fa_quotes tq ".
                                " GROUP BY tq.TradeID) qq ".
                                " ON (qq.max_quote_time=ttq.TimeStart and qq.TradeID=ttq.TradeID) ".
                    " ) lq ".
                    " ON (f.TradeID = lq.TradeID) ".

            ($where ? "WHERE $where" : '' ).

            "ORDER BY (f.CloseTime is null) DESC, COALESCE(f.CloseTime, 0) DESC, f.BeginTime DESC ".
            ( $this->select_limit ? " LIMIT  $this->select_limit " : '');
        } //sqls
    }//class TrackForecastsShow

    //----------------------------------------------------------------------------------------------------

    class objTrackForecastsAdminShow extends objTrackForecastsShow {
            protected $_db_param_date = '%Y-%m-%d %H:%i';
            protected $_db_show_date = '%Y-%m-%d %H:%i:%s';

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function Render($templateFileName='_TrackForecastsAdmin.tpl') {
            return parent::Render($templateFileName);
        } //Render

    } //class TrackForecastsAdminShow

    //----------------------------------------------------------------------------------------------------
    abstract class objActionTrackRecord {
            protected $Response = false;
            protected $Collector = false;
            protected $flag_build = false;
            protected $data = false;
            public $isPerfTable = false;

        public function __construct(xajaxResponse $nResponse) {
            $this->setResponse($nResponse);

            $this->Collector = objTrackRecordCollector::GetInstance();
            $this->Collector->Lock();

            $this->Load();
        } //constructor

        public function __destruct(){
           $this->Collector->Unlock();
        }//destructor

        abstract protected function Render();

        abstract protected function Load();

        abstract protected function Save();

        public function setResponse(xajaxResponse $nResponse) {
            $this->Response = $nResponse;
        } //setResponse

        public function getResponse($force=false) {
            if( $force ) $this->flag_build = false;
            if( $this->flag_build ) return $this->Response;

            $this->Render($this->isPerfTable);
            $this->flag_build = true;
            return $this->Response;
        } //getResponse

    } //class ActionTrackRecord

    //----------------------------------------------------------------------------------------------------

    class objActionTrackRecord_ForecastsShow extends objActionTrackRecord {
            public $flag_effect = false;
            public $flag_active = false;
            public $id = false;
            public $trade = false;
            public $start = false;
            public $finish = false;
            public $system = false;
            public $mode = 'pair';

        protected function hideDiv($divID) {
            $this->Response->addAssign($divID, 'style.display', 'none');
        } //hideDiv

        protected function showDiv($divID) {
            $this->Response->addAssign($divID, 'style.display', 'block');
        } //showDiv

        protected function Load() {
            $this->data['prev']['forecast'] = $this->Collector->getForecastItem();
            $this->data['prev']['track'] = $this->Collector->getTrackItem();
        } //Load

        protected function Save() {
            $this->Collector->setForecastItem(array('start'=>$this->start, 'finish'=>$this->finish));
            $this->Collector->setTrackItem(array('trade'=>$this->trade, 'system'=>$this->system, 'mode'=>$this->mode));
        } //Save

        protected function GenerateID() {
            $this->Load();

            $this->data['prev']['date_id'] =  "trackcell_0_" .$this->data['prev']['forecast']['start'] . "_" .
                                         $this->data['prev']['forecast']['finish'];

            $this->data['prev']['id'] =  $this->data['prev']['forecast']['start'] . "_" .
                                         $this->data['prev']['forecast']['finish'];

            if( 'system'==$this->mode ) {
                $this->system = $this->id;
                $this->data['prev']['id'] = "trackcell_" .
                                            intval($this->data['prev']['track']['system']) . "_" . $this->data['prev']['id'];
            } else {
                $this->trade = $this->id;
                $this->data['prev']['id'] = "trackcell_" .
                                            intval($this->data['prev']['track']['trade']) . "_" . $this->data['prev']['id'];
            }

            $this->data['curr']['id'] = "trackcell_" . intval($this->id) . "_" . $this->start . "_" . $this->finish;
            $this->data['curr']['date_id'] = "trackcell_0_" . $this->start . "_" . $this->finish;

        } //GenerateID

        protected function Render() {
            $this->GenerateID();

            $this->showDiv($this->data['prev']['id'] . '_normal');
            $this->hideDiv($this->data['prev']['id'] . '_selected');
            $this->showDiv($this->data['prev']['id'] . '_date_normal');
            $this->hideDiv($this->data['prev']['id'] . '_date_selected');
            $this->showDiv($this->data['prev']['date_id'] . '_date_normal');
            $this->hideDiv($this->data['prev']['date_id'] . '_date_selected');

            $this->hideDiv($this->data['curr']['id'] . '_normal');
            $this->showDiv($this->data['curr']['id'] . '_selected');
            $this->hideDiv($this->data['curr']['id'] . '_date_normal');
            $this->showDiv($this->data['curr']['id'] . '_date_selected');
            $this->hideDiv($this->data['curr']['date_id'] . '_date_normal');
            $this->showDiv($this->data['curr']['date_id'] . '_date_selected');

            $this->Save();

            if( 'system'!=$this->mode ) $this->RenderForecasts(); //show forecasts if not system mode
        } //Render

        protected function RenderForecasts() {
            $TrackForecastsShow = new objTrackForecastsShow($this->trade, $this->start, $this->finish, $this->system);
            $TrackForecastsShow->enable_active = $this->flag_active;

            if( $this->flag_effect ) $this->Response->addAssign('divTrackForecasts', 'style.display', 'none');
            $this->Response->addAssign("divTrackForecasts","innerHTML", $TrackForecastsShow->Render());
            if( $this->flag_effect ) $this->Response->addScript("new Effect.Appear(\"divTrackForecasts\",{duration:0.6, queue: 'end'});");
        } //RenderForecasts

    } //class ActionTrackRecord_ForecastsShow

    //----------------------------------------------------------------------------------------------------

    class objActionTrackRecord_Show extends objActionTrackRecord {
            public $trade = false;
            public $system = false;
            public $flag_show_active = false;
            public $flag_show_forecasts = true;
            public $flag_effect = false;
            public $mode = 'pair';

            protected $TranslationMessage;

        public function __construct(xajaxResponse $nResponse) {
            parent::__construct($nResponse);

            $this->TranslationMessage = objTranslationMessage::GetInstance();

            $this->Collector->Clear('start');
            $this->Collector->Clear('finish');
        } //constructor

        protected function Render() {
            if( $this->flag_effect ) $this->Response->addScript("new Effect.Fade(\"divTracksMain\",{duration:0.3, queue: 'end'});");

            $this->RenderPairs();

            $lastArr = $this->RenderData($this->isPerfTable);
            $this->Save();
            if( $this->flag_show_forecasts && 'system'!=$this->mode) { // show foreacts for selected system&trade
                $this->RenderForecasts($lastArr);
            }
        } //Render

        protected function RenderPairs() {
            $Pairs = new objPairsSystems();
            $Pairs->system = $this->system;

            if( !$this->system ) {
                $Pairs->order_by_rate = false;
                $Pairs->order_by_sysname = false;
            }

            $flag_notfound = true;
            if( !$Pairs->isEmpty() ) {
                $pairsArr = $Pairs->getAssocArr();

                if( $this->system!=$this->data['system'] ) { //  if system changed rebuild pairs in header

                    $pairsStr = $this->RenderPairItem(0, $this->system, $this->TranslationMessage->GetMessage('_tracks__labelAll'), false);

                    foreach( $pairsArr as $pairItem) { // render pairs
                        $pairsStr .= $this->RenderPairItem($pairItem['TradeID'], $pairItem['SystemID'], $pairItem['Pair']);
                    } // foreach  /render pairs
                    $this->Response->addAssign('divTracks_HeaderPairs', 'innerHTML', $pairsStr);
                } //   /if system changed rebuild pairs in header

                foreach( $pairsArr as $pairItem) { //select pairs
                    $flagON = ($this->trade == $pairItem['TradeID']);
                    $this->RenderDivSelect($pairItem['TradeID'], $flagON);
                    if( $flagON ) $flag_notfound = false;
                } //foreach  /select pairs
            } //if

            if( $flag_notfound ) $this->trade = 0;
            $this->RenderDivSelect(0, !$this->trade);
        } //RenderPairs

        protected function RenderDivSelect($id, $isOn=true) {
            $this->Response->addAssign('divTracks_' . $id . '_separator', 'style.display', 'inline');
            if( !$isOn ) {
                $this->Response->addAssign('divTracks_' . $id . '_normal', 'style.display', 'inline');
                $this->Response->addAssign('divTracks_' . $id . '_selected', 'style.display', 'none');
            } else {
                $this->Response->addAssign('divTracks_' . $id . '_normal', 'style.display', 'none');
                $this->Response->addAssign('divTracks_' . $id . '_selected', 'style.display', 'inline');
            } //if

        } //RenderDivSelect

        protected function RenderPairItem($aTradeID, $aSystemID, $aPair, $aSeparator=true) {
            $Template = new objTemplate();
            $Template->Assign('TradeID', $aTradeID);
            $Template->Assign('SystemID', $aSystemID);
            $Template->Assign('Pair', $aPair);
            $Template->Assign('ShowSeparator', $aSeparator);
            return $Template->Fetch('_Tracks_HeaderPairItem.tpl');
        } //RenderPairItem

        protected function RenderData($isPerfTable=false) {
            $TrackCalculator = new objTrackCalculator();

            $TrackCalculator->system = $this->system;
            $TrackCalculator->short = $this->system || $this->trade;//true;

            $this->mode = 'pair';
            if( !$TrackCalculator->short ) {
                $TrackCalculator->mode = 'system';
                $this->mode = 'system';
                $TrackCalculator->start_year = '2008';
                $TrackCalculator->start_month = '01';
            }  else  {
                $TrackCalculator->selDataKey = $this->trade;
            }

            $TrackCalculator->TranslationMessage = objTranslationMessage::GetInstance();
            $TrackCalculator->enable_active = $this->flag_show_active;

            if( $this->flag_effect ) $this->Response->addAssign('divTracksMain', 'style.display', 'none');

            if( $isPerfTable ) $this->Response->addAssign("divTracksMain", "innerHTML", $TrackCalculator->RenderPerfTable($isPerfTable));//show summary column
            else $this->Response->addAssign("divTracksMain", "innerHTML", $TrackCalculator->Render());//show summary column

            if( $this->flag_effect ) $this->Response->addScript("new Effect.Appear(\"divTracksMain\",{duration:0.6, queue: 'end'});");
            return $TrackCalculator->GetLast();
        } //RenderData

        protected function RenderForecasts($lastArr) {
            $data_id = intval( 'pair'==$this->mode ? $this->trade : $lastArr['TradeID'] ); //XXX

            $this->Response->addScript("xajax_showTrackRecordForecasts('$data_id','".$lastArr['DateStart']."','".$lastArr['DateFinish']."', '".$lastArr['Active']."','".intval($this->system)."','".$this->mode."', '".$this->flag_effect."');");
        } //RenderForecasts

        protected function Load() {
            $this->data = $this->Collector->getTrackItem();
        } //Load

        protected function Save() {
            $this->Collector->setTrackItem(array('trade'=>$this->trade,
                                                 'system'=>$this->system,
                                                 'mode'=>$this->mode,
                                                 'show_active'=>$this->flag_show_active));
        } //Save

    } // class ActionTrackRecord_Show
    //----------------------------------------------------------------------------------------------------

    class objActionTrackRecord_Reload extends objActionTrackRecord {
            public $trade = false;
            public $system = false;
            public $flag_show_active = false;
            public $flag_show_forecasts = true;
            public $flag_effect = false;

            protected $id = false;

        protected function Load() {
            $this->data['forecast'] = $this->Collector->getForecastItem();
            $this->data['track'] = $this->Collector->getTrackItem();
        } //Load

        protected function Save() {
            $this->Collector->setForecastItem(array('start'=>$this->start, 'finish'=>$this->finish));
            $this->Collector->setTrackItem(array('trade'=>$this->trade, 'system'=>$this->system, 'mode'=>$this->mode,'show_active'=>$this->flag_show_active));
        } //Save

        protected function Render() {
            $this->GenerateID();

            $this->RenderItems();
            $this->RenderTotals();
            $this->RenderForecasts();

            $this->Collector->IncCounter();
        } //Render

        protected function RenderForecasts() {
            $Now = new objDate();
            $Start = new objDate($this->data['forecast']['start']);
            $Finish = new objDate($this->data['forecast']['finish']);

            if( $Now->Range($Start, $Finish, true, true) )
                $this->Response->addScript('xajax_showTrackRecordForecasts("'.$this->id.'","'.$this->data['forecast']['start'].'","'.$this->data['forecast']['finish'].'", "'.$this->flag_show_active.'","'.$this->data['track']['system'].'","'.$this->mode.'". "false");');

        } //RenderForecasts

        protected function Calculate($flag_total = false) {
            $TrackCalculator = new objTrackCalculator();
            $TrackCalculator->system = $this->system;
            $TrackCalculator->mode = $this->mode;
            $TrackCalculator->short = $this->system || $this->trade;//true;

            if( 'pair'==$this->mode ) {
                $TrackCalculator->selDataKey = $this->id;
            } else {
                $TrackCalculator->start_year = '2008';
                $TrackCalculator->start_month = '01';
            }

            $TrackCalculator->TranslationMessage = objTranslationMessage::GetInstance();
            $TrackCalculator->enable_active = $this->flag_show_active;
            $TrackCalculator->active_period = !$flag_total;
            return $TrackCalculator->GetData();
        } //Calculate

        protected function RenderItems() {
            $tradeData = $this->Calculate();
            // update data
            foreach($tradeData['dates'] as $DateKey => $itemDate) {
                foreach($tradeData['items'] as $DataID => $itemData ) {
                    $tid = $DataID . '_' . $itemDate['Start'] . '_' . $itemDate['Finish'];
                    $row_id = 'trackrecord__row_' . $tid;
                    $value_id = 'trackcellvalue_' . $tid;
                    if( $this->flag_effect ) $this->Response->addScript("new Effect.Fade(\"$row_id\",{duration:0.3, queue: 'end'});");
                    $value = ($tradeData['data'][$DateKey][$DataID] ? $tradeData['data'][$DateKey][$DataID] : '-');
                    $this->Response->addAssign($value_id . '_normal', 'innerHTML', $value);
                    $this->Response->addAssign($value_id . '_selected', 'innerHTML', $value);
                    if( $this->flag_effect ) $this->Response->addScript("new Effect.Appear(\"$row_id\",{duration:0.5, queue: 'end'});");
                } //foreach pair
            } //foreach date
        } //RenderItems

        protected function RenderTotals() {
            $totalData = $this->Calculate(true);

            foreach($totalData['items'] as $DataID => $itemData ) {
                $row_id = 'trackcell_row__' . $DataID . '_total';
                $value_id = 'trackcellvalue_' . $DataID . '_total';

                if( $this->flag_effect ) $this->Response->addScript("new Effect.Fade(\"$row_id\",{duration:0.3, queue: 'end'});");
                $this->Response->addAssign($value_id, 'innerHTML', $totalData['totals'][$DataID]['pips']);
                if( $this->flag_effect ) $this->Response->addScript("new Effect.Appear(\"$row_id\",{duration:0.5, queue: 'end'});");
            } //foreach pair
        } //RenderTotals

        protected function GenerateID() {
            $this->Load();

            $this->trade = $this->data['track']['trade'];
            $this->show_active = $this->data['track']['show_active'];
            $this->system = $this->data['track']['system'];
            $this->mode = $this->data['track']['mode'];

            $this->id = ('system'==$this->mode ? intval($this->system) : intval($this->trade));
        } //GenerateID

    } //class ActionTrackRecord_Reload

    //----------------------------------------------------------------------------------------------------

    function showTrackRecordForecasts($id, $start, $finish,  $active=false, $system=false, $mode='pair', $effect=false) {
        $Response = new xajaxResponse();

        $ActionForecastsShow = new objActionTrackRecord_ForecastsShow($Response);

        $ActionForecastsShow->id = $id;
        $ActionForecastsShow->start = $start;
        $ActionForecastsShow->finish = $finish;
        $ActionForecastsShow->system = $system;
        $ActionForecastsShow->mode = $mode;
        $ActionForecastsShow->flag_effect = $effect;
        $ActionForecastsShow->flag_active = $active;

        return $ActionForecastsShow->getResponse();
    } //showTrackRecordForecasts

    function showTrackRecord($trade=0, $system=0, $show_forecasts=true, $effect=false) {
      global $config;
        $Response = new xajaxResponse();

        $Staff = new objStaff($config['app_id']);
        if( !$system ) $system = $Staff->GetSystem(false);

        if( !$trade && !$system ) {
            $Response->addAssign('divTracks_HeaderPairs', 'style.display', 'none');
            $Response->addAssign('hline', 'style.display', 'none');
        } else {
            $Response->addAssign('divTracks_HeaderPairs', 'style.display', 'inline');
            $Response->addAssign('hline', 'style.display', 'inline');
        }

        $ActionShow = new objActionTrackRecord_Show($Response);
        $ActionShow->trade = $trade;
        $ActionShow->system = $system;
        $ActionShow->flag_show_active = $Staff->AccessAllowed();
        $ActionShow->flag_show_forecasts = $show_forecasts;
        $ActionShow->flag_effect = $effect;
        return $ActionShow->getResponse();
    } //showTrackRecord

    function reloadTrackRecord($effect=false) {
      global $config;
        $Response = new xajaxResponse();

        $Staff = new objStaff($config['app_id']);

        $ActionReload = new objActionTrackRecord_Reload($Response);
        $ActionReload->flag_effect = $effect;
        $ActionReload->flag_show_active = $Staff->AccessAllowed();
        return $ActionReload->getResponse();
    } //reloadTrackRecord

    //----------------------------------------------------------------------------------------------------

    class objDashboardForecastsShow extends objTrackForecastsShow implements iErrorHandler {
            protected $ChartPeriod = false;

            public $trade_system = false;

        public function __construct() {
            $this->enable_active = true;
            $this->_db = objDataBase::GetInstance();
        }//constructor

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        public function getFields() {
            if( !$this->Prepare() ) return false;
            if( $this->data ) {
                return array_keys($this->data[0]);
            } else return false;
        } //getFields

        public function getFirstTrade() {
            if( !$this->Prepare() ) return false;
            if( $this->data ) {
                return $this->data[0]['TradeID'];
            } else return false;
        } //getFirstTrade

        public function getFirstSystem() {
            if( !$this->Prepare() ) return false;

            if( $this->data ) {
                return $this->data[0]['SystemID'];
            } else return false;
        } //getFirstSystem

        public function getFirstForecast() {
            if( !$this->Prepare() ) return false;

            if( $this->data ) {
                return $this->data[0]['ForecastID'];
            } else return false;
        } //getFirstForecast

        public function getFirstArr() {
            return array('system'=>$this->getFirstSystem(), 'trade'=>$this->getFirstTrade() );
        } //getFirstArr

        public function Find($aSystem, $aTrade) {
            if( !$this->Prepare() ) return false;

            foreach($this->data as $item) {
                if( $aSystem==$item['SystemID'] && $aTrade==$item['TradeID']) return true;
            }//foreach
            return false;
        } // Find

        public function GetData() {
            if( !$this->Prepare() ) return false;

            return $this->data;
        } // GetData

        protected function Prepare() {
            $this->_sqls();

            $this->data = $this->_db->handler->getAll($this->_sql_querys['forecast_list']);
            if( !count($this->data) ) {
                $this->_sqls($this->buildWhere(false));

                $this->data = $this->_db->handler->getAll($this->_sql_querys['forecast_list']);
            }

            if( !$this->data ) return false;

            $this->ChartPeriod =  new objChartPeriod();

            $this->PostPrepare();

            return $this->data;
        } //Prepare

        protected function BuildPeriod($aSystemID, $aTrade, $aMaxDate=false) {
            $this->ChartPeriod->setSystem($aSystemID);
            $this->ChartPeriod->setTrade($aTrade);
            $this->ChartPeriod->setMaxDate($aMaxDate);
            $this->ChartPeriod->Build(true);
            return $this->ChartPeriod->GetPeriod();
        } //BuildPeriod

        public static function ClearCache($templateFileName='_DashboardForecasts.tpl') {
            $id = $this->GenID();

            $tList = new objTemplate('en');
            $tList->caching = true;
            $tList->cache_lifetime = -1;
            $tList->clear_cache($templateFileName, $id);
        } //clearCache

        public function Render($templateFileName='_DashboardForecasts.tpl', $force=false) {
            if( $force ) return parent::Render($templateFileName);
            else {
                $id = $this->GenID();

                $tList = new objTemplate('en');
                $tList->caching = true;

                $tList->cache_lifetime = 20;//-1;

                if( !$tList->is_cached($templateFileName, $id) ) {
                    if( !$this->Prepare() ) return false;
                    $tList->Assign('ForecastArr', $this->data);
                } //if cache not exists

                return $tList->Fetch($templateFileName, $id);
            }
        }//Render

        protected function buildWhere($active=true) {
            $whereArr = array();
            //-----------------------------------------------------------------------------------
            if( $active ) {
                $whereArr[] = "f.CloseTime Is Null";
                $whereArr[] = "f.CloseTime >= UNIX_TIMESTAMP()-24*60*60 ";
                $this->select_limit = 0;
            } //enable active
            else {
                $this->select_limit = 4;
            }
            //-----------------------------------------------------------------------------------
            $where[] = implode(' OR ', $whereArr );
            $where[] = ' s.Active=1 ';

            if( !empty($this->trade_system) ) {
                $twhere = ' ( ';
                $first_item = true;

                foreach($this->trade_system as $item) {

                    $twhere .= ( $first_item ? '' : ' OR ');

                    $twhere .= " ( f.TradeID=".$item['TradeID']." AND f.SystemID=".$item['SystemID'] .' ) ';
                    if( $first_item) $first_item = false;
                } //foreach
                $twhere .= ' ) ';

                $where[] = $twhere;
            } //if set trades sysytems pairs

            $nw = array();
            foreach( $where as $wi)
                if( $wi ) $nw[] = '('.$wi.')';
            $where = $nw;

            return implode(' AND ', $where);
        } //buildWhere

        protected function GenID() {
            $id = 'lastdashboard__';
            $ts = '';
            if( !empty($this->trade_system))
                foreach($this->trade_system as $item) {
                    $ts .= $item['TradeID'].'_'.$item['SystemID'].'__' ;
                } //foreach
            if( $ts ) $id .= md5($ts);
            return $id;
        } //GenID

    } //class objDashboardForecastsShow

    //----------------------------------------------------------------------------------------------------

    class objDashboardCollector extends objArchiveCollector{
            static private $instance;
            static protected $prefix = 'DashboardCollector_';
            protected $_fields = array('system', 'trade', 'forecast', 'fields', 'trade_system');

        static protected function ClassName() {
            return __CLASS__;
        } //ClassName

        public static function GetInstance() {
            if( !isset(self::$instance) ) {
                //$c = __CLASS__;
                $c = self::ClassName();
                self::$instance = new $c;
            }
            return self::$instance;
        } //GetInstance

    } //class DashboardCollector

    //----------------------------------------------------------------------------------------------------

    function ShowDashboardForecast($aTrade, $aSystem, $aForecast ) {
      global $config;

        $Response = new xajaxResponse();

        $DashboardCollector = objDashboardCollector::GetInstance();
        if( $DashboardCollector->isLocked() ) return $Response;
        $fields = $DashboardCollector->fields;
        $DashboardCollector->Lock();
        $DashboardCollector->trade = $aTrade;
        $DashboardCollector->system = $aSystem;

        $prev_forecast = $DashboardCollector->forecast;
        $forecast = $aForecast;

        $DashboardCollector->forecast = $aForecast;

        $ForecastItem = new objDashboardForecastItem($aForecast);
        $Response->addAssign('divDashboardForecast','innerHTML', $ForecastItem->Render(false));
        foreach( $fields as $field ) {
            $Response->addAssign('rowDashboard_'.$prev_forecast.'_'.$field.'_selected', 'style.display', 'none');
            $Response->addAssign('rowDashboard_'.$prev_forecast.'_'.$field.'_normal', 'style.display', 'block');

            $Response->addAssign('rowDashboard_'.$forecast.'_'.$field.'_selected', 'style.display', 'block');
            $Response->addAssign('rowDashboard_'.$forecast.'_'.$field.'_normal', 'style.display', 'none');
        } //foreach

        $DashboardCollector->Unlock();
        return $Response;
    } //ShowDashboardForecast


    function ShowDashboard($usr_id=false) {
      global $config;
        $Response = new xajaxResponse();
        $DashboardCollector = objDashboardCollector::GetInstance();
        $DashboardForecastsShow = new objDashboardForecastsShow();

        if( $usr_id ) {
            $User = new objUserModel($usr_id);
            $DashboardForecastsShow->trade_system = $User->GetTradeSystemArr();
        } //usr_id is nor false

        $Response->addAssign('divDashboard','innerHTML', $DashboardForecastsShow->Render());

        if( $DashboardCollector->isEmpty('trade') || $DashboardCollector->isEmpty('system') ||
           !$DashboardForecastsShow->Find($DashboardCollector->system, $DashboardCollector->trade) )  {

            $DashboardCollector->system = $DashboardForecastsShow->getFirstSystem();
            $DashboardCollector->trade = $DashboardForecastsShow->getFirstTrade();
            $DashboardCollector->forecast = $DashboardForecastsShow->getFirstForecast();
            $DashboardCollector->fields = $DashboardForecastsShow->getFields();
            $DashboardCollector->trade_system = $DashboardForecastsShow->trade_system;
        } //if params are empty or are not in set

        if( !$DashboardCollector->isEmpty() )
            $Response->addScript("xajax_ShowDashboardForecast('".$DashboardCollector->trade."',".
                                                                "'".$DashboardCollector->system."',".
                                                                "'".$DashboardCollector->forecast."'".
                                                                ")");

        return $Response;
    } //ShowDashboard

//-------------------------------------------------------------------------------------------------------
?>
